
import React, { useEffect } from 'react'
import { useSelector } from 'react-redux'
import { StoreType } from '@store/types'
import { Modal } from 'antd-mobile';
import Router from 'next/router'

const alert = Modal.alert;

/**
 * 判断是否需要授权
 * @param page 是否需要授权的界面
 * @param isAuth 是否需要授权
 */
export default function withOauth(Comp: any, isAuth: boolean = true) {

  const Auth = (props: any) => {

    // 判断是否登录
    const isLogin = useSelector<StoreType, any>((store) => !!store.auth.user)

    useEffect(() => {
      if (isAuth !== isLogin) {
        const show = isAuth ? '当前界面需要登录才能进入' : '当前界面不需要登录才能进入'
        alert('提示', <div>{show}</div>, [
          { text: '主页', onPress: () => Router.replace('/') },
          { text: '返回', onPress: () => Router.back() },
        ])
      }
    }, [])

    return isLogin === isAuth ? <Comp {...props}></Comp> : <div></div>
  }

  Auth.getInitialProps = async (ctx: any) => {

    let appProps = {}
    if (typeof Comp.getInitialProps === 'function') {
      appProps = await Comp.getInitialProps(ctx)
    }

    return {
      ...appProps,
    }
  }

  return Auth
}